#!/usr/bin/env python
# coding=utf-8
import redis
import json
import sys
import requests
import urllib
import time
import logmod
import config
import check_playbook_res
import dingding_notice2
#print config.Redis_config['FullHost']

#sys.exit(0)
def RedisConn():
    #r1 = redis.StrictRedis(host='10.0.0.31', port=6379, db=0, password="ansibleapi", socket_timeout=None, connection_pool=None, charset='utf-8', errors='strict', unix_socket_path=None)
    #r1 = redis.Redis(host= redis_host,port = redis_port,db = redis_db)
    r1 = redis.StrictRedis(host=config.Redis_config['Host'], port=config.Redis_config['Port'], db=0, password=config.Redis_config['Passwd'], socket_timeout=None, connection_pool=None, charset='utf-8', errors='strict', unix_socket_path=None)
    return r1
'''
key = r1.lpop("playbook_execute_results")
data  = r1.hget("playbook_execute_results_map",key)



'''


'''
'''
r1 = RedisConn()
#data = r1.lpop("playbook_execute_results_test")

#data = r1.lpop("playbook_execute_results")

def call_fun_info(func):
    def wrapper(*args, **kwargs):
        time.sleep(1)
        print " call func name is: %s " %func.__name__
        return func(*args, **kwargs)
    return wrapper

@call_fun_info
def callback_result(result_post_url,execute_result,try_times):
    try:
        ourheaders = {'Content-Type': 'application/json'}
        r = requests.post(result_post_url, headers=ourheaders, data=json.dumps(execute_result),timeout=1)
        print '======text====='
        print r.text
        print '=====content===='
        print r.content
        if r.status_code == 200:
            return r.text
    except requests.exceptions.Timeout:
        if try_times > 5:
            print "connection timeout, the 5 seconds requests"
            return -1
        try_times += 1
        callback_result(result_post_url, execute_result, try_times)


@call_fun_info
def callback_info(callback_url,data,try_times):
    try:
        ourheaders = {'Content-Type': 'application/x-www-form-urlencoded'}
        r = requests.post(callback_url, headers=ourheaders, data=data,timeout=1)
        print r.text
        print '============content============'
        print r.content
        if r.status_code == 200:
            return r.text
    except requests.exceptions.Timeout:
        if try_times > 5:
            print "connection timeout, the 5 seconds requests"
            return -1
        try_times += 1
        callback_info(callback_url,data,try_times)


@call_fun_info
def callback_progress_stauts(progress_url,try_times):
    try:
        r = requests.get(progress_url,timeout=5)
        if r.status_code == 200:
            return r.text

    except requests.exceptions.Timeout:
        if try_times > 5:
            print "connection timeout, the 5 seconds requests"
            return -1
        try_times += 1
        callback_progress_stauts(progress_url,try_times)

while True:
    num = r1.llen("playbook_execute_results_queue")
    print "there queue len is %d" %(num)
    if num >= 1:
        key = r1.lpop("playbook_execute_results_queue")
        #key="1143"
        print "pop key:%s" %(key)
        data = r1.hget("playbook_execute_results_map",key)
        if data:
            new_data = json.loads(data)
        if new_data:
            print type(new_data)
            print new_data.keys()
            print new_data['response_url']
            print '\n  ============================== \n'
            print new_data['status']
            print '\n  ============================== \n'
            print new_data['taskid']
            print '\n  ============================== \n'
            print new_data['result']
            print type(new_data['result'])

            print new_data['response_url2']
            if new_data['response_url']:
                pass
            else:
                print 'Error: response_url not exist'
                continue

            if new_data['response_url2']:
                pass
            else:
                print 'Error: response_url not exist'
                continue
        else:
            print 'could not get data from playbook_execute_results_map in %s' %(key)

        result_post_url = new_data['response_url2'] + '/sendpost/true'
        time.sleep(2)
        print "callbackresult_post_url"
        progress_url = new_data['response_url'] + '/status/true'
        time.sleep(2)
        print progress_url
        callback_url = new_data['response_url'] + '/sendpost/asf'
        time.sleep(2)
        print callback_url


        data = 'step=callback !'
        try_times = 1
        callback_info(callback_url,data,try_times)
        #callback_info(callback_url,new_data['cmdline'])
        #callback_info(callback_url,new_data['taskid'])
        taskinfo = "taskid: " + str(new_data['taskid']) + "  cmdline:" + str(new_data['cmdline'])
        logmod.callback_log(taskinfo,"info")
        #logmod.callback_log(str(new_data['taskid']),"info")

        callback_progress_stauts(progress_url,try_times)

        if new_data['result'] and result_post_url:
            callback_result(result_post_url,new_data['result'],try_times)
            # 取最后10行试试
            nums = len(new_data['result'])
            print new_data['result'][num-5:]
            task_status = check_playbook_res.check_playbook_res(new_data['result'])
            task_info = {}
            task_info['taskid'] = new_data['taskid']
            task_info['cmdline'] = new_data['cmdline']
            task_info['status'] = task_status

        logmod.callback_log(json.dumps(task_info),"info")

        if task_status == False:
            try_times = 1
            res = dingding_notice2.dingding_notice(json.dumps(task_info),try_times)

            if res != True:
                logmod.callback_log(res,"error")


        #print json.dumps(new_data)
        #print json.dumps(new_data['cmdline'])


    print 'Callback Stage: there are not data in queue,sleep 2s'
    time.sleep(2)
